package com.css.fxfzcpxx.modules.informationAchievement.service.impl;

import com.css.fxfzcpxx.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzcpxx.base.attachment.service.AttachmentInfoService;
import com.css.fxfzcpxx.base.response.RestResponse;
import com.css.fxfzcpxx.common.utils.BeanUtil;
import com.css.fxfzcpxx.common.utils.UpdateUtil;
import com.css.fxfzcpxx.constants.FxfzConstants;
import com.css.fxfzcpxx.constants.YNEnum;
import com.css.fxfzcpxx.modules.informationAchievement.entity.InfAchievement;
import com.css.fxfzcpxx.modules.informationAchievement.param.DisasterLossAssessmentParam;
import com.css.fxfzcpxx.modules.informationAchievement.param.QueParams;
import com.css.fxfzcpxx.modules.informationAchievement.repository.InfAchievementRepository;
import com.css.fxfzcpxx.modules.informationAchievement.service.InfAchievementService;
import com.css.fxfzcpxx.modules.informationAchievement.vo.ExportVo;
import com.css.fxfzcpxx.modules.informationAchievement.vo.InfAchievementVo;
import com.css.fxfzcpxx.modules.informationAchievement.vo.ListVo;
import com.css.fxfzcpxx.modules.informationAchievement.vo.OtherSystemInfoVo;
import com.css.fxfzcpxx.util.*;
import com.css.fxfzcpxx.web.PlatformSessionContext;
import com.css.fxfzcpxx.zcpt.sys.entity.SOrg;
import com.css.fxfzcpxx.zcpt.sys.entity.SUser;
import com.css.fxfzcpxx.zcpt.sys.service.SysOrgService;
import com.css.fxfzcpxx.zcpt.sys.service.impl.SUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class InfAchievementServiceImpl implements InfAchievementService {
    @Resource
    InfAchievementRepository infAchievementRepository;

    @Resource
    AttachmentInfoService attachmentInfoService;
    @Resource
    SUserServiceImpl sUserServiceImpl;

    @Resource
    SysOrgService sysOrgService;
    @Value("${image.localDir}")
    private String localDir;

    @Override
    public Map<String, Object> getPage(QueParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = infAchievementRepository.getPage(queParams,curPage, pageSize);
        return page;
    }

    @Override
    public void save(InfAchievement infAchievement) {
        String userId = PlatformSessionContext.getUserID();
        //获取用户名称
        String sUser = sUserServiceImpl.getSUser(userId);
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String org = sysOrgService.getOrgById(userInfo.getOrgId());
        SOrg sOrg = CreateGson.createGson().fromJson(org, SOrg.class);

        infAchievement.setId(UUIDGenerator.getUUID());
        infAchievement.setCreateUser(userId);
        infAchievement.setPublishingUnit(sOrg.getName());
        infAchievement.setCreateTime(new Date());
        infAchievement.setDelFlag(YNEnum.N.toString());
        infAchievement.setReleaseStatus(YNEnum.Y.toString());
        infAchievementRepository.save(infAchievement);
    }

    @Override
    public void recallOrPublish(QueParams queParams) {
        infAchievementRepository.recallOrPublish(queParams.getReleaseStatus(),Arrays.asList(queParams.getIds().split(",")),new Date());
    }

    @Override
    public void delete(String ids) {
        infAchievementRepository.delete(Arrays.asList(ids.split(",")));
    }

    @Override
    public InfAchievementVo findById(String id) {
        InfAchievementVo infAchievementVo=new InfAchievementVo();
        InfAchievement infAchievement=infAchievementRepository.findById(id);
        UpdateUtil.copyNullProperties(infAchievement, infAchievementVo);
        if (PlatformObjectUtils.isNotEmpty(infAchievement.getAppendix())){
            infAchievementVo.setAppendixAtt(attachmentInfoService.queryFile(infAchievement.getAppendix()));
        }
        if (PlatformObjectUtils.isNotEmpty(infAchievement.getAchievementUpload())){
            infAchievementVo.setAchievementUploadAtt(attachmentInfoService.queryFile(infAchievement.getAchievementUpload()));
        }
        return infAchievementVo;
    }

    @Override
    public List<InfAchievement> getkeywordManageData(String ids) {
        return infAchievementRepository.getkeywordManageData(Arrays.asList(ids.split(",")));
    }

    @Override
    public void keywordUpdate(ListVo listvo) {
        List<InfAchievement> list = listvo.getList();
        for(InfAchievement item:list){
            infAchievementRepository.keywordUpdate(item.getId(),item.getKeyword());
        }
    }

    @Override
    public void update(InfAchievement infAchievement) {
        infAchievement.setUpdateTime(new Date());
        infAchievement.setUpdateUser(PlatformSessionContext.getUserID());

        if("0".equals(infAchievement.getReleaseStatus())){
            infAchievementRepository.publishedDataupdate(infAchievement);
        }else{
            infAchievementRepository.unpublishedDataupdate(infAchievement);
        }

    }

    @Override
    public void catalogDownload(HttpServletResponse response, String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<ExportVo> list=infAchievementRepository.getExportData(idList);
        //List<InfAchievement> infAchievements = this.getkeywordManageData(ids);
        if (list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "信息成果数据信息统计", "信息成果数据信息", ExportVo.class, "信息成果数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //地震灾害损失评估
    @Override
    public Map<String, Object> disasterLossAssessment(DisasterLossAssessmentParam queParams, int curPage, int pageSize) {
        Map<String, Object> map = infAchievementRepository.disasterLossAssessment(queParams, curPage, pageSize);
        List<InfAchievementVo> list = (List<InfAchievementVo>) map.get("rows");
        for (InfAchievementVo infAchievementVo : list) {
            String path=localDir+infAchievementVo.getAttachPath();
            infAchievementVo.setAttachPath(path);
        }
        map.put("rows",list);
        return map;
    }

    @Override
    public List<InfAchievementVo> getLatestData() {
        List<InfAchievementVo> latestData = infAchievementRepository.getLatestData();
        for(InfAchievementVo item:latestData){
            if (PlatformObjectUtils.isNotEmpty(item.getAchievementUpload())){
                item.setAchievementUploadAtt(attachmentInfoService.queryFile(item.getAchievementUpload()));
            }
        }
        return latestData;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dockingOtherSystem(OtherSystemInfoVo otherSystemInfoVo) throws Exception {
        MultipartFile file = otherSystemInfoVo.getFile();

        //获取文件名称
        String fileName = file.getOriginalFilename();
        //获取文件上传的本地路径
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
        String savePath = localDir + dateDir;
        //构建文件
        assert fileName != null;
        //上传文件
        String realFileName = uploadFile(fileName, savePath, file);
        //构建实体类
        AttachmentInfoEntity attachmentInfoEntity = buildAttachment(fileName, dateDir, realFileName);
        //保存附件到数据库
        int flag = 0;
        if (ObjectUtils.isNotEmpty(attachmentInfoEntity)) {
            flag = attachmentInfoService.singleSave(attachmentInfoEntity);
        }
        if (flag == 1) {
            InfAchievement infAchievement = new InfAchievement();
            infAchievement.setAchievementDate(new Date());
            infAchievement.setId(UUIDGenerator.getUUID());
            infAchievement.setCreateTime(new Date());
            infAchievement.setDelFlag(YNEnum.N.toString());
            infAchievement.setReleaseStatus("0");
            infAchievement.setCreateUser(otherSystemInfoVo.getCreateUser());
            infAchievement.setPublishingUnit(otherSystemInfoVo.getPublishingUnit());
            infAchievement.setDataOrigin(otherSystemInfoVo.getDataOrigin());
            infAchievement.setKeyword(otherSystemInfoVo.getKeyword());
            infAchievement.setAchievementUpload(attachmentInfoEntity.getAttachId());
            String achievementName = otherSystemInfoVo.getAchievementName();
            if(achievementName.endsWith(".docx") || achievementName.endsWith(".xlsx")){
                otherSystemInfoVo.setAchievementName(achievementName.substring(0,achievementName.lastIndexOf(".")));
            }

            if (FxfzConstants.FXFZ_YPG.equals(otherSystemInfoVo.getDataOrigin())) {
                infAchievement.setAchievementColumn("评估报告-地震灾害损失预评估");
            } else if (FxfzConstants.FXFZ_AQBZ.equals(otherSystemInfoVo.getDataOrigin())) {
                infAchievement.setAchievementColumn("评估报告-重大活动期间地震灾害风险评估");
            } else if (FxfzConstants.FXFZ_XCZH.equals(otherSystemInfoVo.getDataOrigin())) {
                if("1".equals(otherSystemInfoVo.getSign())){
                    infAchievement.setAchievementColumn("评估报告-地震灾害损失评估");
                }else{
                    infAchievement.setAchievementColumn("灾情报表-地震现场人员伤亡分布及致死原因调查报表");
                }
            }
            BeanUtils.copyProperties(otherSystemInfoVo, infAchievement);
            infAchievementRepository.save(infAchievement);
        }
    }

    private String uploadFile(String fileName, String savePath,MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        String preFileName = fileName.substring(0,fileName.lastIndexOf("."));
        // .jpg  .pdf  .txt  .docs
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 拼文件名  真实的文件名称
        String realFileName = preFileName + "_"  + System.currentTimeMillis() + fileType;
        //判断文件夹是否存在如果不存在则创建
        if(!new File(savePath).exists()){
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, realFileName);
        multipartFile.transferTo(file);
        return realFileName;
    }

    private AttachmentInfoEntity buildAttachment(String fileName, String dateDir, String realFileName) {
        AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
        attachmentInfoEntity.setAttachId(StringUtils.buildPrimaryId());
        attachmentInfoEntity.setAttachName(fileName);
        attachmentInfoEntity.setAttachPath( dateDir + "/" + realFileName);
        attachmentInfoEntity.setFileDirId(localDir);
        attachmentInfoEntity.setIsValid("1");
        attachmentInfoEntity.setIsCompleted("1");
        return attachmentInfoEntity;
    }

}
